package ycl.security.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import ycl.security.entity.SecurityUser;
import ycl.security.service.UserDetailsService;
import ycl.system.entity.SysRole;
import ycl.system.entity.SysUser;
import ycl.system.mapper.SysMenuMapper;
import ycl.system.mapper.SysRoleMapper;
import ycl.system.mapper.SysUserMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ycl
 * @date 2022/8/25 0025 20:38:22
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

	@Resource
	private SysUserMapper sysUserMapper;
	@Resource
	private SysRoleMapper sysRoleMapper;
	@Resource
	private SysMenuMapper sysMenuMapper;

	/**
	 * 根据用户名加载用户
	 *
	 * @param username 用户名
	 * @return 用户详情
	 * @throws UsernameNotFoundException 用户未找到异常
	 */
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		log.info("UserDetailsServiceImpl . loadUserByUsername . 根据用户名加载用户");
		SysUser user = getUserByUsername(username);
		List<String> rolePermission = new ArrayList<>();
		List<String> menuPermission = new ArrayList<>();
		if (user.getType() == 0) {
			//超级管理员
			rolePermission = sysRoleMapper.selectAllIdentification();
		} else {
			//其他角色
			List<SysRole> sysRoles = sysRoleMapper.selectEnableByUserId(user.getId());
			if (CollUtil.isNotEmpty(sysRoles)) {
				for (SysRole v : sysRoles) {
					rolePermission.add(v.getIdentification());
				}
			}
		}
		List<String> authorizes = new ArrayList<>(rolePermission);
		List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(authorizes.toString());
		return new SecurityUser(user, authorityList);
	}


	@Override
	public SysUser getUserByUsername(String username) {
		SysUser user = sysUserMapper.selectByUsername(username);
		if (user == null)
			user = sysUserMapper.selectByMobile(username);
		if (user == null)
			user = sysUserMapper.selectByWechatId(username);
		if (user == null) {
			log.error("user not found ---> {}", username);
			throw new UsernameNotFoundException("未找到用户");
		}

		Assert.isTrue(user.getStatus() == 0, "用户被禁用");
		Assert.isFalse(user.getLocked(), "用户被锁定不可登录");
		return user;
	}
}
